//
//  ExaminaStatisticsDetailController.m
//  Coach_HaiGeEr
//
//  Created by liuchen on 2018/10/22.
//  Copyright © 2018年 海格尔. All rights reserved.
//

#import "ExaminaStatisticsDetailController.h"
#import "LXDatePickerViewController.h"
#import "TFDropDownMenuView.h"
#import "ExaminaStatisticsFirstCell.h"
#import "ExaminaStatisticsSecondCell.h"

@interface ExaminaStatisticsDetailController ()<TFDropDownMenuViewDelegate,UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong) TFDropDownMenuView *selectView;
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) UIView *selectTimeView;
@property (nonatomic,copy) NSString *selectType;
@property (nonatomic,copy) NSArray *typeArr;
@property (nonatomic,copy) NSDictionary *passDic;
@property (nonatomic,copy) NSArray *listArr;
@property (nonatomic,copy) NSArray *studentListArr;
@property (nonatomic,assign) NSInteger selectJudge;//是否自定义选择
@end

@implementation ExaminaStatisticsDetailController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithHexString:@"#eeeeee"];
    [self.view addSubview:self.tableView];
    [self loadData];
}

#pragma mark ==========加载数据==========
- (void)loadData{
    [self showLoading];
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_enter(group);
    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
        [dic setValue:@"本月" forKey:@"dateStr"];
        [dic setValue:[BCMHelper dateChangeToString:[NSDate date]] forKey:@"stateDate"];
        [dic setValue:[BCMHelper dateChangeToString:[NSDate date]] forKey:@"endDate"];
        [dic setValue:[NSNumber numberWithInteger:self.type] forKey:@"subjectType"];
        [[NetworkEngine sharedClient] GETByToken:EXAMINAMANAGEMENRATEOFPASSING data:dic success:^(id responseObject) {
            if ([[responseObject objectForKey:@"code"] integerValue]==1) {
                self.passDic = [responseObject objectForKey:@"data"];
            } else if ([[responseObject objectForKey:@"code"] integerValue]==2) {
                [self hideHUD];
                self.block(YES);
            } else {
                [self showMessage:[responseObject objectForKey:@"msg"]];
            }
            dispatch_group_leave(group);
        } failure:^(NSString *error) {
            [self showError:error];
            dispatch_group_leave(group);
        }];
    });
    dispatch_group_enter(group);
    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
        [dic setValue:[BCMHelper monthSringFromDate:[NSDate date]] forKey:@"dateStr"];
        [dic setValue:[NSNumber numberWithInteger:self.type] forKey:@"subjectType"];
        [[NetworkEngine sharedClient] GETByToken:EXAMINAMANAGEMENSTUDENTLIST data:dic success:^(id responseObject) {
            if ([[responseObject objectForKey:@"code"] integerValue]==1) {
                self.listArr = [responseObject objectForKey:@"data"];
            } else if ([[responseObject objectForKey:@"code"] integerValue]==2) {
                [self hideHUD];
                self.block(YES);
            } else {
                [self showMessage:[responseObject objectForKey:@"msg"]];
            }
            dispatch_group_leave(group);
        } failure:^(NSString *error) {
            [self showError:@"加载失败"];
            dispatch_group_leave(group);
        }];
    });
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        [self hideHUD];
        //界面刷新
        [self.tableView reloadData];
    });
}
- (void)loadRateData{
    [self showLoading];
    ExaminaStatisticsFirstCell *cellOne = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    ExaminaStatisticsFirstCell *cellTwo = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setValue:self.selectType forKey:@"dateStr"];
    [dic setValue:cellOne.timeBtn.titleLabel.text forKey:@"stateDate"];
    [dic setValue:cellTwo.timeBtn.titleLabel.text forKey:@"endDate"];
    [dic setValue:[NSNumber numberWithInteger:self.type] forKey:@"subjectType"];
    [[NetworkEngine sharedClient] GETByToken:EXAMINAMANAGEMENRATEOFPASSING data:dic success:^(id responseObject) {
        [self hideHUD];
        if ([[responseObject objectForKey:@"code"] integerValue]==1) {
            self.passDic = [responseObject objectForKey:@"data"];
            [self.tableView reloadData];
        } else if ([[responseObject objectForKey:@"code"] integerValue]==2) {
            self.block(YES);
        } else {
            [self showMessage:[responseObject objectForKey:@"msg"]];
        }
    } failure:^(NSString *error) {
        [self showError:@"加载失败"];
    }];
}
- (void)loadStudentListWithDate:(NSString *)dateStr{
    [self showLoading];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setValue:dateStr forKey:@"dateStr"];
    [dic setValue:[NSNumber numberWithInteger:self.type] forKey:@"subjectType"];
    [[NetworkEngine sharedClient] GETByToken:EXAMINAMANAGEMENSTUDENTLIST data:dic success:^(id responseObject) {
        [self hideHUD];
        if ([[responseObject objectForKey:@"code"] integerValue]==1) {
            self.listArr = [NSMutableArray arrayWithArray:[responseObject objectForKey:@"data"]];
            [self.tableView reloadData];
        } else if ([[responseObject objectForKey:@"code"] integerValue]==2) {
            self.block(YES);
        } else {
            [self showMessage:[responseObject objectForKey:@"msg"]];
        }
    } failure:^(NSString *error) {
        [self showError:@"加载失败"];
    }];
}

#pragma mark ==========懒加载==========
- (UIView *)selectTimeView{
    if (!_selectTimeView) {
        _selectTimeView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 110*SCALEUNIT)];
        UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, 20*SCALEUNIT, SCREEN_WIDTH, 90*SCALEUNIT)];
        backView.backgroundColor = [UIColor whiteColor];
        UIButton *touchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        touchBtn.frame = CGRectMake(25*SCALEUNIT, 0, 200*SCALEUNIT, 90*SCALEUNIT);
        [touchBtn addTarget:self action:@selector(changeTime:) forControlEvents:UIControlEventTouchUpInside];
        [touchBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
        [touchBtn setTitle:[BCMHelper monthSringFromDate:[NSDate date]] forState:UIControlStateNormal];
        [touchBtn.titleLabel setFont:[UIFont systemFontOfSize:LoginFont-3]];
        [touchBtn setTitleColor:[UIColor colorWithHexString:@"#666666"] forState:UIControlStateNormal];
        touchBtn.showsTouchWhenHighlighted = YES;
        [backView addSubview:touchBtn];
        [_selectTimeView addSubview:backView];
    }
    return _selectTimeView;
}
- (TFDropDownMenuView *)selectView{
    if (!_selectView) {
        self.typeArr = @[@"本月", @"近三个月",@"近六个月",@"近一年",@"自定义"];
        NSMutableArray *data1 = [NSMutableArray arrayWithObjects:self.typeArr, nil];
        _selectView = [[TFDropDownMenuView alloc] initWithFrame:CGRectMake(0,25*SCALEUNIT, SCREEN_WIDTH, 90*SCALEUNIT) firstArray:data1 secondArray:nil titleArray:@[@"本月"]];
        _selectView.delegate = self;
    }
    return _selectView;
}
- (UITableView *)tableView{
    
    if (_tableView == nil) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 20*SCALEUNIT, self.view.frame.size.width, SCREEN_HEIGHT-SYSTEM_TOP-120*SCALEUNIT-20*SCALEUNIT-100*SCALEUNIT) style:UITableViewStylePlain];
        _tableView.tableHeaderView = self.selectView;
        _tableView.tableFooterView = [[UIView alloc]init];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLineEtched;
        [_tableView setSeparatorInset:UIEdgeInsetsMake(0, 30*SCALEUNIT, 0, 30*SCALEUNIT)];
        [_tableView setSeparatorColor:[UIColor colorWithHexString:@"#eeeeee"]];
        [_tableView registerClass:[ExaminaStatisticsFirstCell class] forCellReuseIdentifier:@"ExaminaStatisticsFirstCellOne"];
        [_tableView registerClass:[ExaminaStatisticsFirstCell class] forCellReuseIdentifier:@"ExaminaStatisticsFirstCellTwo"];
        [_tableView registerClass:[ExaminaStatisticsSecondCell class] forCellReuseIdentifier:@"ExaminaStatisticsSecondCell"];
    }
    return _tableView;
}

#pragma mark ==========UITableView代理方法==========
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3+self.listArr.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section==0) {
        return 2;
    } else if (section==1) {
        return 1;
    } else if (section==2) {
        return 0;
    } else {
        return self.listArr==nil?0:[[[self.listArr objectAtIndex:section-3] objectForKey:@"data"] count];
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==1) {
        return 600*SCALEUNIT;
    }else{
        return 100*SCALEUNIT;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *finalCell;
    if (indexPath.section==0) {
        ExaminaStatisticsFirstCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ExaminaStatisticsFirstCellOne" forIndexPath:indexPath];
        cell.row = indexPath.row;
        WS(ws);
        cell.block = ^(UIButton *btn) {
            btn.userInteractionEnabled = YES;
            if (!self.selectJudge) return ;
            LXDatePickerViewController *pickerVC = [[LXDatePickerViewController alloc] initWithSelectedDate:nil];
            pickerVC.cancleBlock = ^{
                [ws dismissViewControllerAnimated:YES completion:nil];
            };
            pickerVC.selectBlock = ^(NSString *dateString) {
                [ws dismissViewControllerAnimated:YES completion:nil];
                if (indexPath.row==0) {
                    ExaminaStatisticsFirstCell *cellTwo = [ws.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
                    if (![ws compareStareDay:dateString WithEndDay:cellTwo.timeBtn.titleLabel.text]) {
                        [ws showMessage:@"截至时间不能在当前时间之前"];
                        return;
                    } else{
                        [btn setTitle:dateString forState:UIControlStateNormal];
                        [ws loadRateData];
                    }
                } else {
                    ExaminaStatisticsFirstCell *cellOne = [ws.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
                    if (![ws compareStareDay:cellOne.timeBtn.titleLabel.text WithEndDay:dateString]) {
                        [ws showMessage:@"截至时间不能在当前时间之前"];
                        return;
                    } else{
                        [btn setTitle:dateString forState:UIControlStateNormal];
                        [ws loadRateData];
                    }
                }
            };
            pickerVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
            [ws presentViewController:pickerVC animated:YES completion:nil];
        };
        finalCell = cell;
    } else if (indexPath.section==1) {
        ExaminaStatisticsSecondCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ExaminaStatisticsSecondCell" forIndexPath:indexPath];
        cell.passDic = self.passDic;
        finalCell = cell;
    } else if (indexPath.section==2) {
        
    } else {
        if (indexPath.section>2) {
            ExaminaStatisticsFirstCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ExaminaStatisticsFirstCellTwo" forIndexPath:indexPath];
            cell.timeBtn.userInteractionEnabled = NO;
            cell.tlabel.text = [[[[self.listArr objectAtIndex:indexPath.section-3] objectForKey:@"data"] objectAtIndex:indexPath.row] objectForKey:@"studentName"];
            [cell.timeBtn setTitle:[[[[[self.listArr objectAtIndex:indexPath.section-3] objectForKey:@"data"] objectAtIndex:indexPath.row] objectForKey:@"examResult"] integerValue]==1?@"通过":@"未通过" forState:UIControlStateNormal];
            finalCell = cell;
        }
    }
    return finalCell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0) {
        return 0;
    } else if (section==1) {
        return 20*SCALEUNIT;
    } else if (section==2) {
        return 110*SCALEUNIT;
    } else {
        return self.listArr==nil?0:90*SCALEUNIT;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *finallView;
    if (section==0) {
    } else if (section==1) {
        UIView *view = [[UIView alloc] init];
        view.backgroundColor = [UIColor colorWithHexString:@"#eeeeee"];
        finallView = view;
    } else if (section==2) {
        return self.selectTimeView;
    } else {
        if (self.listArr != nil) {
            UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 90*SCALEUNIT)];
            backView.backgroundColor = [UIColor colorWithHexString:@"#eeeeee"];
            UILabel *tLabel = [[UILabel alloc] initWithFrame:CGRectMake(25*SCALEUNIT, 0, 300*SCALEUNIT, CGRectGetHeight(backView.frame))];
            tLabel.textAlignment = NSTextAlignmentLeft;
            tLabel.font = [UIFont systemFontOfSize:LoginFont-3];
            tLabel.textColor = [UIColor colorWithHexString:@"#666666"];
            tLabel.text = [[self.listArr objectAtIndex:section-3] objectForKey:@"nowDate"];
            [backView addSubview:tLabel];
            finallView = backView;
        }
    }
    return finallView;
}


#pragma mark ==========TFDropDownMenuViewDelegate==========
- (void)menuView:(TFDropDownMenuView *)menu tfColumn:(NSInteger)column WithSelectJudge:(BOOL)selectJudge{
    
}
- (void)menuView:(TFDropDownMenuView *)menu selectIndex:(TFIndexPatch *)index{
    self.selectType = index.section==4?@"":[self.typeArr objectAtIndex:index.section];
    self.selectJudge = index.section==4?YES:NO;
    if (index.section != 4) {
        ExaminaStatisticsFirstCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
        [cell.timeBtn setTitle:index.section==0?[NSString stringWithFormat:@"%@-01",[BCMHelper monthSringFromDate:[NSDate date]]]:[BCMHelper getPriousorLaterDateFromDate:[NSDate date] withMonth:index.section==1?-3:index.section==2?-6:-12] forState:UIControlStateNormal];
        [self loadRateData];
    } else{
    }
}

#pragma mark ==========changeTime(更换月份)==========
- (void)changeTime:(UIButton *)btn{
    LXDatePickerViewController *pickerVC = [[LXDatePickerViewController alloc] initWithSelectedDate:nil];
    pickerVC.style = 1;
    WS(ws);
    pickerVC.cancleBlock = ^{
        [ws dismissViewControllerAnimated:YES completion:nil];
    };
    pickerVC.selectBlock = ^(NSString *dateString) {
        [ws dismissViewControllerAnimated:YES completion:nil];
        [btn setTitle:dateString forState:UIControlStateNormal];
        [ws loadStudentListWithDate:dateString];
    };
    pickerVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    [ws presentViewController:pickerVC animated:YES completion:nil];
}

#pragma mark ==========判断当前日期是否过期( 0相等,返回1过期,2没过期 )==========
- (NSInteger)compareStareDay:(NSString *)startDay WithEndDay:(NSString *)endDay{
    NSComparisonResult result = [startDay compare:endDay];
    if (result == NSOrderedDescending) {
        //在指定时间前面+过了指定时间=过期
        return 0;
    } else{
        return 1;
    }
}

- (void)dealloc{
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
